package com.yunianvh.usbcamera;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.pedro.rtmp.utils.ConnectCheckerRtmp;
import com.pedro.rtplibrary.view.OpenGlView;
import com.yunianvh.demo.R;
import com.yunianvh.libusbcamera.USBCameraHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends AppCompatActivity {
    private TextView textView, textView2;
    private OpenGlView openGlView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.camera_tv);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //修改分辨率可参照这个方法
//                    USBCameraHelper.getInstance().setPreviewSize(1920, 1080, 1024 * 1024 * 5, 0);
//                    USBCameraHelper.getInstance().stopPreview();
//                    USBCameraHelper.getInstance().startPreview();

                if (USBCameraHelper.getInstance().isRecording()) {
                    USBCameraHelper.getInstance().stopRecord();
                    textView.setText("开始录制");
                } else {
                    String recoderPath = getExternalFilesDir(null).getAbsolutePath() + "/" + new SimpleDateFormat("dd HH:mm:ss").format(new Date()) + ".mp4";
                    USBCameraHelper.getInstance().startRecord(recoderPath);
                    textView.setText("关闭录制");
                }
            }
        });
        EditText editText = findViewById(R.id.camera_et);
        textView2 = findViewById(R.id.camera_tv2);
        textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (USBCameraHelper.getInstance().isStreaming()) {
                    USBCameraHelper.getInstance().stopStream();
                    textView2.setText("开始推流");
                } else {
                    String url = editText.getText().toString();
                    if (TextUtils.isEmpty(url)) {
                        Toast.makeText(MainActivity.this, "请输入推流地址", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    USBCameraHelper.getInstance().startStream(url);
                    textView2.setText("关闭推流");
                }
            }
        });
        ImageView imageView = findViewById(R.id.camera_iv);
        findViewById(R.id.camera_iv_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                USBCameraHelper.getInstance().takePicture(new USBCameraHelper.PictureBack() {
                    @Override
                    public void onPictureBitMap(Bitmap bmp) {
                        imageView.setImageBitmap(bmp);
                    }
                });
            }
        });

        openGlView = (OpenGlView) findViewById(R.id.camera_opengl_view);
        init();

//        if (ContextCompat.checkSelfPermission(this, permission[0]) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, permission, 111);//添加还未授予的权限
//        } else {
//            auth();
//        }
    }

    public void init() {
        USBCameraHelper.getInstance().init(this, openGlView, new ConnectCheckerRtmp() {
            @Override
            public void onConnectionStartedRtmp(@NonNull String s) {

            }

            @Override
            public void onConnectionSuccessRtmp() {

            }

            @Override
            public void onConnectionFailedRtmp(@NonNull String s) {

            }

            @Override
            public void onNewBitrateRtmp(long l) {

            }

            @Override
            public void onDisconnectRtmp() {

            }

            @Override
            public void onAuthErrorRtmp() {

            }

            @Override
            public void onAuthSuccessRtmp() {

            }
        });

        USBCameraHelper.getInstance().setUSBCameraCallBack(new USBCameraHelper.USBCameraCallBack() {
            @Override
            public void onOpenCamera(boolean isOpen) {
                Log.e("USBCameraHelper", "onOpenCamera isOpen: " + isOpen);
                if (!isOpen && USBCameraHelper.getInstance() != null) {
                    USBCameraHelper.getInstance().stop();
                    USBCameraHelper.getInstance().destory();
                }
            }

            @Override
            public void onPreview(boolean isPreview) {
                Log.e("USBCameraHelper", "onPreview isPreview: " + isPreview);
                if (!isPreview && USBCameraHelper.getInstance() != null) {
                    USBCameraHelper.getInstance().stop();
                    USBCameraHelper.getInstance().destory();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = true;//是否有权限没有通过
        if (111 == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = false;
                }
            }
            if (!hasPermissionDismiss) {
                textView.setText("测试软件，请勿商用");
            } else {
                auth();
            }
        }
    }

    private void auth() {
        String encodedString = readConfigFileContent();
        String authData = "5oqA5pyv5ZKo6K+i77yaVzE4MzE5MDQ1OTUyCua6kOeggeWcsOWdgO+8mmh0dHBzOi8vZ2l0ZWUuY29tL3l1bmlhbnZoL3VzYmNhbWVyYS5naXQK5Y2a5Li75Li76aG177yaaHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM1MzUwNjU0P3R5cGU9YmxvZwrova/ku7bkuLvopoHkvJjljJbpooTop4jlu7bml7bku6Xlj4rlvIDmupDlupPnmoTkuIDkupvluLjop4Hpl67popjvvIzlpoLmnIlDYW1lcmHnm7jlhbPlvIDlj5HpnIDmsYLlj6/ogZTns7vljZrkuLs7CuWNmuS4u+acieWkmuS4qumfs+inhumikeiQveWcsOmhueebru+8jOWMheaLrOS9huS4jemZkOS6jnJ0bXDlupPjgIFydHNw5bqT44CBV2ViUlRD5bqT44CBR0IyODE4MeW6k+etieetie+8mw==";
        if (TextUtils.isEmpty(encodedString) || !encodedString.trim().contains(authData)) {
            textView.setText("测试软件，请勿商用");
        }
        String decodedString = decodeBase64ToString(encodedString);
        Log.e("TAG", "欢迎使用USBCamera\n" + decodedString);
    }

    public String readConfigFileContent() {
        StringBuilder content = new StringBuilder();
        try {
            InputStream inputStream = this.openFileInput("config.ini");
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    content.append(line);
                }
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

    public static String decodeBase64ToString(String input) {
        byte[] data = Base64.decode(input, Base64.DEFAULT);
        return new String(data);
    }

    @Override
    protected void onDestroy() {
        if (USBCameraHelper.getInstance() != null) {
            USBCameraHelper.getInstance().destory();
        }
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        if (USBCameraHelper.getInstance() != null) {
            USBCameraHelper.getInstance().start();
        }
        super.onStart();
    }

    @Override
    protected void onStop() {
        if (USBCameraHelper.getInstance() != null) {
            USBCameraHelper.getInstance().stop();
        }
        super.onStop();
    }

}
